﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Beetle.Sl.EditorControl.Core;
using Beetle.Sl.EditorControl.Controls;

namespace Beetle.Sl.EditorControl.ToolBars.SetFontColor
{
    [ToolBarItemAttribute]
    public class SetFontColorToolBar : ToolBarItem
    {
        public const string COMMANDTEXT = "SetFontStyle";
        private UIElement _popupContent;

        public override string Name
        {
            get
            {
                return "SetFontColor";
            }
        }

        public SetFontColorToolBar()
        {
            this.ImageButtonUri = new Uri("/Beetle.Sl.EditorControl;component/ToolBars/SetFontColor/FontColor.png", UriKind.Relative);
        }

        public override ToolBarItemVisualTypeEnum ToolBarItemVisualType
        {
            get
            {
                return ToolBarItemVisualTypeEnum.DropDownButton;
            }
        }

        public override UIElement PopupContent
        {
            get
            {
                if (this._popupContent == null)
                {
                    ColorSelectPanel colorSelectPanel = new ColorSelectPanel();
                    colorSelectPanel.SelectedValue += new EventHandler(colorSelectPanel_OnValueChanged);
                    this._popupContent = colorSelectPanel;
                }

                return this._popupContent;
            }
        }

        public override void OnCommand(object arg)
        {
            this.IsSelected = !this.IsSelected;
            this.IsOpenPopup = !this.IsOpenPopup;
        }

        void colorSelectPanel_OnValueChanged(object sender, EventArgs e)
        {
            ColorSelectPanel colorSelectPanel = sender as ColorSelectPanel;
            string color = colorSelectPanel.Value.ToString().TrimStart(new char[] { '#' });

            SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(
                byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(6, 2), System.Globalization.NumberStyles.HexNumber)));

            this.Editor.ExcuteCommand(SetFontColorToolBar.COMMANDTEXT, new object[] { Run.ForegroundProperty, brush });
            this.IsSelected = false;
            this.IsOpenPopup = false;
        }

        public override void UpdateVisual()
        {
            this.IsEnabled = !this.Editor.RichTextBoxInst.IsReadOnly;
        }
    }
}
